<?php
namespace admin\action;

use herosphp\bean\Beans;
use herosphp\http\HttpRequest;
use herosphp\session\Session;
use herosphp\utils\AjaxResult;
use herosphp\web\WebUtils;

/**
 * login action
 * @package admin\action
 * @author yangjian<yangjian102621@gmail.com>
 */
class LoginAction extends CommonAction {

    protected $serviceBean = 'admin.adminManager.service';

    //登陆页面
    public function index( HttpRequest $request ) {
        $service = Beans::get($this->serviceBean);
		$uri = urldecode($request->getParameter('uri'));
		if($uri == '/admin/login/index' || !$uri || strpos($uri,'export')!==false){//导出url不跳回
			$uri = '/admin/index/index';
		}
        

		//是否开启验证码验证

		$settingService = Beans::get('admin.adminSetting.service');
		$verifyCodeEnable = $settingService->getSetting('verifyCode');
		$this->assign('verifyCodeEnable',$verifyCodeEnable);

		$this->assign('uri',$uri);
        if ( $service->isLogin() ) {
			header('location:'.$uri);
        }
        //$this->setView("login");
        $new = $request->getParameter('new');
        if(!$new) {
            $this->setView("login");
        }else {
            $this->setView("login_new");
        }
    }

    //登陆验证
    public function signin(HttpRequest $request) {
        $username = $request->getParameter('uname');
        $password = $request->getParameter('pwd');
        $scode = $request->getParameter('scode');

		$settingService = Beans::get('admin.adminSetting.service');
		$denyIp = $settingService->getSetting('denyLoginIp');
		$iplist = explode(',',$denyIp);
		
		$ip = WebUtils::getClientIP();

		//ip校验
        /*
		foreach($iplist as $v){
			if(matchIp($ip,$v)){
				AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, 'ip 被禁用');
			}
		}*/
		$verifyCodeEnable = $settingService->getSetting('verifyCode');

        Session::start();
		//是否开启验证码验证

		if($verifyCodeEnable == 'on'){
			if ( strtoupper($scode) != $_SESSION['scode'] ) {
				AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '验证码错误');
			}
		}


        $service = Beans::get($this->serviceBean);
        $user = $service->login($username, $password);
        if ( $user == false ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '登陆失败，用户名或者密码错误');
        }

        if ( $user['status'] == 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '你的账户已被禁用，请联系管理员');
        }

        AjaxResult::ajaxSuccessResult();

    }

    //退出登陆
    public function logout(HttpRequest $request) {
        $service = Beans::get($this->serviceBean);
        $service->logout();
        location("/admin/login/index");
    }
}
